﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Seesmic.Sdp.Extensibility;
using System.Threading;
using Seesmic.Sdp.Utils;
using PTiRouZ.Net.SilverLight.Api.HelloTipi;
using PTiRouZ.Net.SilverLight.Api;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

using Seesmic.Sdp.Utils;

namespace Seesmic.HelloTipi
{
    public class HelloTipiDirectMessagesTimeLineItemsProvider : ITimelineItemsProvider
    {

        #region Fields

        private Timer _Timer;
        private System.Windows.Threading.DispatcherTimer _timer;

        private int messageId = 0;
        private int messageSentId = 0;

        private HelloTipiAccount _account;

        //private ObservableCollection<direct_messages> directMessagesSent;
        //private ObservableCollection<direct_messages> directMessagesReceive;

        public apitxt api;

        #endregion Fields

        #region Properties

        public HelloTipiTimeLine Timeline
        {
            get;
            private set;
        }

        #endregion Properties

        #region ITimelineItemsProvider Members

        public event EventHandler<TimelineItemEventArgs> ItemAdded;

        public event EventHandler<TimelineItemEventArgs> ItemRemoved;

        #region Constructors

        public HelloTipiDirectMessagesTimeLineItemsProvider(HelloTipiAccount Account)
        {
            //HelloTipiPlugin.LogInfo("Constructeur de HelloTipiDirectMessagesTimeLineItemsProvider");

            _account = Account;

            this.Timeline = new HelloTipiTimeLine();

            this.api = new apitxt(Account.Username, Account.Password, "Seesmic Desktop 2");

            this.api.APICallError += delegate(object sender, ApiErrorEventArgs e)
            {
                HelloTipiPlugin.ShowDialogNotification("Erreur de l'api", "{0}", DialogNotificationButtons.OK, e.Message);
            };

            this.api.DirectMessagesCompleted += delegate(object sender, DirectMessagesEventArgs e)
            {
                //HelloTipiPlugin.LogInfo("api_DirectMessagesCompleted : " + messageId);

                CreateItemContainer(e.result, ref messageId, false);

                if (messageSentId > 0)
                    this.api.dmSent(null, messageSentId);
                else
                    this.api.dmSent();
            };


            this.api.dmSentCompleted += delegate(object sender, dmSentEventArgs e)
            {
                //HelloTipiPlugin.LogInfo("api_dmSentCompleted : " + messageSentId);

                CreateItemContainer(e.result, ref messageSentId, true);
            };

            _Timer = new Timer(OnTimerTick, null, 0, 30000);

            /*System.Windows.Threading.DispatcherTimer _timer = new System.Windows.Threading.DispatcherTimer();
            _timer.Interval = new TimeSpan(0, 0, 10); // 10 secondes

            _timer.Tick += delegate(object sender, EventArgs e)
            {
                HelloTipiPlugin.LogInfo("OnTimerTick");

                if (messageId > 0)
                    this.api.DirectMessages(null, messageId);
                else
                    this.api.DirectMessages();

                if (messageSentId > 0)
                    this.api.dmSent(null, messageSentId);
                else
                    this.api.dmSent();
            };

            this._timer.Start();*/

        }
        #endregion Constructors


        public void OnItemProcessed(ProcessingResult result)
        {
            if (result.Blocked == false && result.Error == null)
            {
                Timeline.Add(result.TimelineItemContainer);
            }
        }

        private void OnItemAdded(TimelineItemEventArgs e)
        {
            var handler = ItemAdded;

            if (handler != null)
            {
                handler(this, e);
            }
        }

        private void OnItemRemoved(TimelineItemEventArgs e)
        {

            //HelloTipiPlugin.LogInfo("Private OnItemRemoved " + e.TimelineItemContainer.TimelineItem.Id);

            Timeline.Remove(e.TimelineItemContainer);

            var handler = ItemRemoved;

            if (handler != null)
            {
                handler(this, e);
            }
        }

        private void OnTimerTick(object state)
        {
            //HelloTipiPlugin.LogInfo("OnTimerTick");

            if (messageId > 0)
                this.api.DirectMessages(null, messageId);
            else
                this.api.DirectMessages();
            
        }

        /*public IEnumerable<direct_messages> Combine(IEnumerable<direct_messages> col1, IEnumerable<direct_messages> col2)
        {
            foreach (direct_messages item in col1)
                yield return item;

            foreach (direct_messages item in col2)
                yield return item;
        }*/

        private void CreateItemContainer(ObservableCollection<direct_messages> messages, ref int messid, bool isSent)
        {
            if (messages != null)
            {

                // HelloTipiPlugin.LogInfo("CreateItemContainer");

                int _messid = messid;

                //foreach (direct_messages DirectMessages in receive.OrderByDescending(x => x.created_at))
                messages.ForEach(delegate(direct_messages message)
                {
                    HelloTipiTimeLineItem Item = new HelloTipiTimeLineItem
                    {
                        Id = message.id.ToString(),
                        Text = message.text,
                        DateTime = DateTime.ParseExact(message.created_at, "ddd MMM d H:mm:ss zzz yyyy", CultureInfo.InvariantCulture),
                        User = message.sender,
                        Account = this._account,
                        Site = HelloTipiPlugin.getSite(message.sender_screen_name),
                        isFamilyTimeline = false,
                        isPrivateTimeline = true,
                        isSent = isSent,
                    };

                    TimelineItemContainer container = new TimelineItemContainer(Item);
                    container.AddAction(new MentionAction(Item.Username));
                    container.AddAction(new PrivateAction(Item.Username));
                    container.AddAction(new DeleteAction(int.Parse(Item.Id), OnItemRemoved));
                    container.AddQuickAction(new MentionAction(Item.Username));
                    container.AddQuickAction(new PrivateAction(Item.Username));

                    if (isSent)
                        container.HighlightColor = ItemHighlightColors.PrivateSent;
                    else
                        container.HighlightColor = ItemHighlightColors.PrivateReceived;

                    SynchronizationHelper.Post(OnItemAdded, new TimelineItemEventArgs(container));

                    if (_messid < message.id)
                        _messid = message.id;
                });

                messid = _messid;
            }
        }

        #endregion
    }
}
